<template>
  <div class="user-profile-container">
    <!-- 用户信息头部 -->
    <div class="user-header">
      <div class="user-info">
        <div class="avatar-container">
          <el-avatar :size="150" :src="getAvatarUrl(userInfo.avatar)"></el-avatar>
        </div>
        <div class="user-right-info">
          <div class="nickname">{{ userInfo.nickName || '用户昵称' }}</div>
          <div class="username">小番薯号：{{ userInfo.userName || '用户账号' }} <span class="ip-location">IP属地：{{
            userInfo.loginIp || '未知' }}</span></div>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-num">{{ userStats.followCount || 0 }}</div>
              <div class="stat-label">关注</div>
            </div>
            <div class="stat-item">
              <div class="stat-num">{{ userStats.fansCount || 0 }}</div>
              <div class="stat-label">粉丝</div>
            </div>
            <div class="stat-item">
              <div class="stat-num">{{ userStats.likeCount || 0 }}</div>
              <div class="stat-label">获赞</div>
            </div>
            <div class="stat-item">
              <div class="stat-num">{{ userStats.collectCount || 0 }}</div>
              <div class="stat-label">收藏</div>
            </div>
          </div>

          <div class="user-intro">{{ userInfo.intro || '这个人很懒，什么都没留下' }}</div>
          <div class="user-city" v-if="userInfo.city">{{ userInfo.city }}</div>

          <div class="action-buttons" v-if="!isSelf">
            <el-button type="danger" round size="small" @click="handleFollow">
              {{ isFollowed ? '已关注' : '关注' }}
            </el-button>
            <el-button type="default" round size="small" icon="el-icon-message">私信</el-button>
          </div>
          <!-- <div class="action-buttons" v-else>
            <el-button type="default" round size="small" icon="el-icon-edit" @click="handleEditProfile">
              编辑资料
            </el-button>
          </div> -->
        </div>
      </div>
    </div>

    <!-- 内容选项卡 -->
    <div class="content-tabs">
      <div class="tab-header">
        <div class="tab-item" :class="{ active: activeTab === 'notes' }" @click="switchTab('notes')" ref="notesTab">
          笔记
        </div>
        <div class="tab-item" :class="{ active: activeTab === 'collected' }" @click="switchTab('collected')" ref="collectedTab">
          收藏
        </div>
        <div class="tab-item" :class="{ active: activeTab === 'liked' }" @click="switchTab('liked')" ref="likedTab">
          点赞
        </div>
      </div>

      <!-- 笔记内容 -->
      <div class="tab-content">
        <!-- 笔记列表 -->
        <div v-if="activeTab === 'notes'" class="notes-container" :class="{ 'fade-in': tabAnimationActive }">
          <div v-if="notesList.length === 0" class="empty-content">
            <i class="el-icon-document"></i>
            <p>暂无笔记内容</p>
          </div>
          <div v-else class="notes-grid">
            <div v-for="note in notesList" :key="note.id" class="note-card" @click="viewNoteDetail(note.id)">
              <div class="note-cover">
                <img :src="note.coverImg" alt="笔记封面">
              </div>
              <div class="note-title">{{ note.title }}</div>
              <div class="note-stats">
                <span><i class="el-icon-view"></i> {{ note.viewCount }}</span>
                <span><i class="el-icon-star-on"></i> {{ note.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 收藏列表 -->
        <div v-if="activeTab === 'collected'" class="notes-container" :class="{ 'fade-in': tabAnimationActive }">
          <div v-if="collectedList.length === 0" class="empty-content">
            <i class="el-icon-star-off"></i>
            <p>暂无收藏内容</p>
          </div>
          <div v-else class="notes-grid">
            <div v-for="note in collectedList" :key="note.id" class="note-card" @click="viewNoteDetail(note.id)">
              <div class="note-cover">
                <img :src="note.coverImg" alt="笔记封面">
              </div>
              <div class="note-title">{{ note.title }}</div>
              <div class="note-stats">
                <span><i class="el-icon-view"></i> {{ note.viewCount }}</span>
                <span><i class="el-icon-star-on"></i> {{ note.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 点赞列表 -->
        <div v-if="activeTab === 'liked'" class="notes-container" :class="{ 'fade-in': tabAnimationActive }">
          <div v-if="likedList.length === 0" class="empty-content">
            <i class="el-icon-star-off"></i>
            <p>暂无点赞内容</p>
          </div>
          <div v-else class="notes-grid">
            <div v-for="note in likedList" :key="note.id" class="note-card" @click="viewNoteDetail(note.id)">
              <div class="note-cover">
                <img :src="note.coverImg" alt="笔记封面">
              </div>
              <div class="note-title">{{ note.title }}</div>
              <div class="note-stats">
                <span><i class="el-icon-view"></i> {{ note.viewCount }}</span>
                <span><i class="el-icon-star-on"></i> {{ note.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑个人资料对话框 -->
    <!-- <el-dialog title="编辑个人资料" :visible.sync="editProfileVisible" width="500px">
      <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="80px">
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" action="/api/file/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="profileForm.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input type="textarea" v-model="profileForm.intro" placeholder="介绍一下自己吧"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="profileForm.city" placeholder="请输入所在城市"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editProfileVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitProfileForm">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
// import { getUser, updateUser } from "@/api/xfs/user/user";
// 导入API函数，但不要重复定义
import { getUserStats, getUserNotes, getUserCollected, getUserLiked, followUser, unfollowUser } from "@/api/xfs/user/userProfile";
import { updateUser } from "@/api/xfs/user/user";

export default {
  name: "UserProfile",
  data() {
    return {
      userId: null,
      isSelf: false,
      isFollowed: false,
      defaultAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      userInfo: {},
      userStats: {
        followCount: 0,
        fansCount: 0,
        likeCount: 0,
        collectCount: 0
      },
      activeTab: 'notes',
      notesList: [],
      collectedList: [],
      likedList: [],
      loading: false,
      editProfileVisible: false,
      profileForm: {
        userId: null,
        avatar: '',
        nickName: '',
        intro: '',
        city: ''
      },
      profileRules: {
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ]
      },
      tabAnimationActive: false
    };
  },
  computed: {
    // 获取当前登录用户的头像
    currentUserAvatar() {
      return this.getAvatarUrl(this.$store.getters.avatar);

    }
  },
  created() {
    // 从路由参数获取用户ID
    this.userId = this.$route.params.id;

    // 如果路由中没有指定用户ID，则使用当前登录用户的ID
    if (!this.userId) {
      // 直接从 state 获取 id
      this.userId = this.$store.state.user.id;
      // 确保有有效的用户ID
      if (!this.userId) {
        console.warn("未能获取有效的用户ID，将使用默认ID");
        this.userId = 1; // 默认ID，通常是管理员
      }
    }

    // 判断是否是当前登录用户
    this.isSelf = String(this.userId) === String(this.$store.state.user.id);

    // console.log("当前登录用户ip :", this.$store.state.loginIp);
    // console.log("当前显示的用户 :", this.userId);
    // console.log("当前登录的用户ID:", this.$store.state.user.id);
    // console.log("是否为当前用户:", this.isSelf);

    this.getUserInfo();
    this.getUserStats(this.userId);
    this.loadNotes();
  },
  methods: {
    // 添加一个方法处理头像URL
    getAvatarUrl(avatar) {
      // if (!avatar) {
      //   return this.defaultAvatar;
      // }
      // if (avatar.startsWith('http') || avatar.startsWith('data:')) {
      //   return avatar;
      // }
      // console.log("avatar:", process.env.VUE_APP_BASE_API + avatar);
      // return process.env.VUE_APP_BASE_API + avatar;
      return "http://localhost" + avatar;
    },

    // 获取用户基本信息
    getUserInfo() {
      this.loading = true;
      console.log("当前user信息:", this.$store.state.user);


      try {
        // 如果是当前登录用户，直接使用store中的用户信息
        if (this.isSelf) {
          // 从store中获取当前用户信息
          this.userInfo = {
            userId: this.$store.state.user.id,
            // nickName: this.$store.state.user.name,
            nickName: this.$store.state.user.nickName,
            userName: this.$store.getters.username || this.$store.state.user.name,
            avatar: this.$store.state.user.avatar,
            loginIp: this.$store.getters.loginIp || "未知",
            intro: this.$store.state.user.intro || "这个人很懒，什么都没留下",
            city: this.$store.getters.city || ""
          };

          this.loading = false;
        } else {
          // 如果不是当前用户，则需要查询用户信息
          import("@/api/xfs/user/user").then(module => {
            const { getUser } = module;
            getUser(this.userId)
              .then(response => {
                if (response && response.data) {
                  this.userInfo = response.data;
                  console.log("API返回的用户信息:", this.userInfo);
                  
                  // 确保头像URL正确处理
                  if (!this.userInfo.avatar) {
                    this.userInfo.avatar = this.defaultAvatar;
                  }
                } else {
                  this.userInfo = this.getDefaultUserInfo();
                }
              })
              .catch(error => {
                console.error("获取用户信息失败:", error);
                this.userInfo = this.getDefaultUserInfo();
              })
              .finally(() => {
                this.loading = false;
              });
          });
        }
      } catch (error) {
        console.error("获取用户信息出错:", error);
        this.userInfo = this.getDefaultUserInfo();
        this.loading = false;
      }
      
    },

    // 获取默认用户信息
    getDefaultUserInfo() {
      return {
        userId: this.userId,
        nickName: "测试用户",
        userName: "testuser",
        loginIp: "127.0.0.1",
        intro: "这是一个测试账号",
        city: "北京"
      };
    },

    // 获取用户统计数据
    getUserStats(userId) {
      getUserStats(userId)
        .then(response => {
          if (response.data) {
            this.userStats = response.data;
            this.isFollowed = response.data.isFollowed || false;
          }
        })
        .catch(() => {
          this.userStats = {
            followCount: 0,
            fansCount: 0,
            likeCount: 0,
            collectCount: 0
          };
        });
    },

    // 加载笔记数据
    loadNotes() {
      const loadFunctions = {
        notes: () => getUserNotes(this.userId),
        collected: () => getUserCollected(this.userId),
        liked: () => getUserLiked(this.userId)
      };

      const dataTargets = {
        notes: 'notesList',
        collected: 'collectedList',
        liked: 'likedList'
      };

      if (loadFunctions[this.activeTab]) {
        loadFunctions[this.activeTab]()
          .then(response => {
            this[dataTargets[this.activeTab]] = response.data || [];
          })
          .catch(() => {
            this[dataTargets[this.activeTab]] = [];
          });
      }
    },

    // 查看笔记详情
    viewNoteDetail(noteId) {
      // 找到被点击的笔记卡片元素
      const noteCards = document.querySelectorAll('.note-card');
      let clickedCard = null;
      
      noteCards.forEach(card => {
        if (card.getAttribute('data-note-id') == noteId) {
          clickedCard = card;
        }
      });
      
      if (clickedCard) {
        // 添加点击动画效果
        clickedCard.classList.add('note-card-click');
        setTimeout(() => {
          clickedCard.classList.remove('note-card-click');
          // 显示消息并跳转
          this.$message.info(`查看笔记 ${noteId} 详情`);
          // 当笔记详情页准备好后，可以取消注释下面的代码
          // this.$router.push(`/note/${noteId}`);
        }, 300);
      } else {
        // 如果找不到元素，直接显示消息
        this.$message.info(`查看笔记 ${noteId} 详情`);
      }
    },

    // 关注/取消关注用户
    handleFollow() {
      const action = this.isFollowed ? unfollowUser : followUser;
      action(this.userId)
        .then(() => {
          this.isFollowed = !this.isFollowed;
          this.$message.success(this.isFollowed ? '关注成功' : '已取消关注');
          // 更新关注数和粉丝数
          this.getUserStats(this.userId);
        })
        .catch(() => {
          this.$message.error('操作失败，请稍后重试');
        });
    },

    // // 编辑个人资料
    // handleEditProfile() {
    //   this.profileForm = {
    //     userId: this.userInfo.userId,
    //     avatar: this.userInfo.avatar,
    //     nickName: this.userInfo.nickName,
    //     intro: this.userInfo.intro || '',
    //     city: this.userInfo.city || ''
    //   };
    //   this.editProfileVisible = true;
    // },

    // 头像上传成功回调
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.profileForm.avatar = res.data || URL.createObjectURL(file.raw);
      } else {
        this.$message.error('头像上传失败');
      }
    },

    // 头像上传前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 提交个人资料表单
    submitProfileForm() {
      this.$refs.profileForm.validate(valid => {
        if (valid) {
          updateUser(this.profileForm)
            .then(() => {
              this.$message.success('个人资料更新成功');
              this.editProfileVisible = false;
              this.getUserInfo(); // 重新获取用户信息
            })
            .catch(() => {
              this.$message.error('更新失败，请稍后重试');
            });
        }
      });
    },

    // 添加新的方法
    switchTab(tab) {
      if (this.activeTab === tab) return;
      
      // 添加点击动画效果
      const tabRef = this.$refs[tab + 'Tab'];
      if (tabRef) {
        tabRef.classList.add('tab-click-effect');
        setTimeout(() => {
          tabRef.classList.remove('tab-click-effect');
        }, 300);
      }
      
      // 内容切换动画
      this.tabAnimationActive = false;
      setTimeout(() => {
        this.activeTab = tab;
        this.$nextTick(() => {
          this.tabAnimationActive = true;
        });
      }, 150);
      
      // 加载对应的数据
      this.loadNotes();
    }
  },
  watch: {
    activeTab() {
      this.loadNotes();
    },
    '$route.params.id'(newId) {
      // 路由参数变化时更新用户ID
      this.userId = newId || this.$store.getters.userId;
      if (!this.userId) {
        this.userId = 1;
      }

      // 更新是否为当前用户的标志
      this.isSelf = String(this.userId) === String(this.$store.getters.userId);

      console.log("路由变化 - 当前显示的用户ID:", this.userId);
      console.log("路由变化 - 当前登录的用户ID:", this.$store.getters.userId);

      this.getUserInfo();
      this.getUserStats(this.userId);
      this.loadNotes();
    }
  }
};
</script>

<style scoped>
.user-profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
}

.user-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  width: 100%;
  max-width: 700px;
  margin-left: 50px;
  /* 向右偏移 */
}

.avatar-container {
  margin-right: 80px;
}

.avatar-container .el-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 150px;
  height: 150px;
}

.user-right-info {
  flex: 1;
  padding-top: 15px;
  max-width: 450px;
}

.nickname {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.username {
  font-size: 13px;
  color: #999;
  margin-bottom: 15px;
}

.ip-location {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.user-stats {
  display: flex;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.stat-num {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-right: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.user-intro {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  line-height: 1.5;
  max-width: 500px;
}

.user-city {
  font-size: 12px;
  color: #999;
  display: inline-block;
  background-color: #f8f8f8;
  padding: 2px 8px;
  border-radius: 10px;
  margin-top: 5px;
  margin-bottom: 15px;
}

.action-buttons {
  margin-top: 10px;
}

.action-buttons .el-button--danger {
  background-color: #ff2442;
  border-color: #ff2442;
}

.content-tabs {
  margin-top: 40px;
  max-width: 800px;
  margin: 40px auto 0;
}

.tab-header {
  display: flex;
  justify-content: center;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
  padding-bottom: 0;
  /* 移除底部内边距 */
}

.tab-item {
  padding: 12px 30px 12px 30px;
  /* 调整上下内边距 */
  font-size: 16px;
  cursor: pointer;
  position: relative;
  color: #666;
}

.tab-item.active {
  color: #ff2442;
  font-weight: bold;
}

.tab-item.active:after {
  content: '';
  position: absolute;
  bottom: -1px;
  /* 确保下划线紧贴底部边框 */
  left: 30%;
  width: 40%;
  height: 3px;
  background-color: #ff2442;
}

.notes-container {
  min-height: 200px;
  padding-top: 20px;
  /* 增加顶部内边距 */
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #999;
}

.empty-content i {
  font-size: 50px;
  margin-bottom: 15px;
  color: #ddd;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
}

.note-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.note-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.note-cover {
  height: 0;
  padding-bottom: 100%;
  position: relative;
  overflow: hidden;
}

.note-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.note-card:hover .note-cover img {
  transform: scale(1.05);
}

.note-title {
  padding: 8px;
  font-size: 12px;
  line-height: 1.4;
  height: 34px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  color: #333;
}

.note-stats {
  display: flex;
  justify-content: space-between;
  padding: 0 8px 8px;
  font-size: 11px;
  color: #999;
}

.note-stats i {
  margin-right: 4px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #ff2442;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 50%;
}

@media screen and (max-width: 992px) {
  .notes-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .notes-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .user-info {
    flex-direction: column;
  }

  .avatar-container {
    margin-right: 0;
    margin-bottom: 15px;
    text-align: center;
  }

  .user-right-info {
    text-align: center;
  }

  .user-stats {
    justify-content: center;
  }
}

@media screen and (max-width: 576px) {
  .notes-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 添加新的动画样式 */
.tab-click-effect {
  animation: tabPulse 0.3s ease;
}

@keyframes tabPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.fade-in {
  animation: fadeIn 0.4s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.note-card-click {
  animation: cardClick 0.3s ease;
}

@keyframes cardClick {
  0% { transform: scale(1); box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1); }
  50% { transform: scale(0.95); box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.2); }
  100% { transform: scale(1); box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1); }
}

/* 增强现有的悬停效果 */
.note-card {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.note-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.tab-item {
  transition: all 0.3s ease;
}

.tab-item:hover:not(.active) {
  color: #ff6b81;
  transform: translateY(-2px);
}

.tab-item.active {
  transition: color 0.3s ease, font-weight 0.3s ease;
}

.tab-item.active:after {
  transition: all 0.3s ease;
}
</style>